var wxUtil = require('../../../utils/wxUtil.js');
var util = require('../../../utils/util.js');
var ajax = require('../../../utils/ajax.js');
var common = require('../../../utils/common.js');
var PageBase = require('../../../common/PageBase.js');
var WxParse = require('../../../utils/wxParse/wxParse.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    isgroups:"",
    isseckill:"",
    dataLoaded: false,
    shop: {},
    address: {},
    goodsList: [],
    orderType: '',//

    isSelfGet: 1, //默认到店自取
    noAddr: false,//默认有收货地址
    addressId: '',//
    optionAddrId: '',

    orderId: null,
    goodsId: '',

    wxPayParams: '',
    wxPaySucUrl: '',

    coupon: {},
    couponId: '',
    couponList: [],
    couponAmout: '', //优惠卷金额
    useCoupon: true,  // 默认是没有选中优惠券
    couponListLen: '',

    orderAmount: 0,
    toPayAmount: '0', //待支付金额

    // userCard: [],
    // userCardNames: [],
    // cardIndex: 0,

    rmPostAmount: '',
    radioItems: [
      { name: '快递配送', value: '1', checked: true},
      { name: '到店自取', value: '0' }
    ],
    activeIndex: 0,
    cardIndex: 0,
    address: {},
    goodsList: [],
    shop:[],
    num:"",
    feetrans: 0,
    index: null
  },


  /**
   * 页面加载
   */
  onLoad: function (options) {
    //debugger;
    var _self = this;
    // var skuId = "", teamid = "", goodsId = "", amount = "", tmpOrderId="";
    // if (typeof (options.skuId) != "undefined" && options.skuId != ""){
    //   skuId  = JSON.parse(options.skuId);
    // };
    // if (typeof (options.teamid) != "undefined" && options.teamid != "") {
    //   teamid = JSON.parse(options.teamid);
    // };
    // if (typeof (options.goodsId) != "undefined" && options.goodsId != "") {
    //   goodsId = JSON.parse(options.goodsId);
    // };
    // if (typeof (options.amount) != "undefined" && options.amount != "") {
    //   amount = JSON.parse(options.amount);
    // };
    var toData = {
      // teamid: teamid || '',
      // goodsId: goodsId || '',
      // skuId: skuId || '',
      // amount: amount || '',
      tmpOrderId: JSON.parse(options.tmpOrderId)

    };
    //debugger;
    this._options = options;
    // _self._actId = options.actId;
    // _self._actType = options.actType;
    // _self._groupBuyId = options.groupBuyId;
    // if (options.addressId) {
    //     toData.addressId = options.addressId;
    // }
    this.setData(toData);
    //debugger;
  },


  onShow: function () {
    var optionAddrId = this.data.optionAddrId;
    if (optionAddrId) {
      this._resetAddr(optionAddrId);
    } else {
      this.showSalt();
    }
  },


  /**
   * 页面初始化数据
   */
  showSalt: function () {
    var $this = this;
    var uid = app.getUid();
    // var goodsId = this.data.goodsId;
    // var skuId = this.data.skuId;
    // var amount = this.data.amount;
    var ajaxUrl = 'm=order&c=index&a=tmp';
    var ajaxParams = {
      uid:uid,
      id: $this.data.tmpOrderId
    };
    //debugger;
    ajax.G({
      url: ajaxUrl,
      data: ajaxParams,
      success: (res) => {

        if(res.code == 1){
          util.showWarn(res.msg);
        }
       
        var result = res.data;
        var feetrans = parseFloat(result.goodslist[0].goods[0].feetrans); //邮费

        //判断是不是团购商品
        if (typeof (result.isgroups) != "undefined" && result.isgroups == "1"){
            this.setData({
              isgroups: "1",
              teamid: result.teamid,
              groupsmoney: result.groupsmoney
            })
        }
        var orderAmount = parseFloat(result.money); //订单金额
        //var toPayAmount = parseFloat(result.toPayAmount); //应付款
        // var userCard = result.userCard; //是否可以使用会员卡支付
        // var userCardNames = [];
        // userCardNames.push('微信支付');
        // if (userCard.length > 0) {
        //   userCard.forEach(function (item) {
        //     userCardNames.push(item.card_name);
        //   })
        // }

        //shopInfo.init('shopInfoData', $this);
        //$this._orderAmount = orderAmount;
        //$this._toPayAmount = toPayAmount;
        //$this._couponCode = result.couponCode;

        //result.address 为空的时候是数组格式，不为空的时候是json格式

        
        if (result.address.length != 0) {
          //debugger;
          $this._noAddr = false;
          var address = result.address[0];
          var addressId = result.address[0].id;
        } else {
          $this._noAddr = true;
        }
        if (!!result.coupon){
          var couponListLen = result.coupon.length;
        }

        $this.setData({
          dataLoaded: true,
          isseckill: result.isseckill,
          //orderType: result.orderType,
          address: address || '',
          addressId: addressId || '',
          couponListLen: couponListLen,
          couponList: result.coupon,
          goodsList: result.goodslist,
          orderAmount: orderAmount.toFixed(2),
          toPayAmount: result.money.toFixed(2),
          feetrans: feetrans.toFixed(0),
          //userCard: userCard,
          //userCardNames: userCardNames,
          noAddr: $this._noAddr,

          aids: result.aids,
          gids: result.gids,
          nums: result.nums,
          goodsId: result.gids

        });

       // $this._getCouponList();

      }
    });

  },


  /**
   * 微信支付
   */
  skip: function (e) {
    //var formId = e.detail.formId;
    this.confirmGoods();
    //common.submitForm(formId);
  },


  /**
   * 会员卡支付
   */
  // _cartPaySkip: function (e) {
  //   var _self = this;
  //   var formId = e.detail.formId;
  //   util.confirm('确认支付', function () {
  //     _self.confirmGoods();
  //   });
  //   common.submitForm(formId);
  // },


  /**
   *支付 
   */
  confirmGoods: function () {
    //debugger
    var {
      gids,
      couponId,
      aids,
      addressId,
      nums,
      orderId,
      isseckill,
      isSelfGet,
      isgroups,
      teamid
    } = this.data;

    // var actId = this._actId;
    // var actType = this._actType;
    // var cid = 0;
    // var pay_type = 2;
    // var recommend = app.getRecommend() || 0;
    var $this = this;
    var ajaxUrl, ajaxParams;

    //couponId = couponId ? couponId : coupon.id || '';

    if (isSelfGet == 1 && addressId == ''){
        util.showWarn("请填写收货地址");
        return;
    }

    // 如果订单已经存在
    if (orderId) {
      this._payAgain();
      return;
    }
    // 如果是到店自取，就不传地址id
    if (isSelfGet == 0){
      addressId = ""
    }

    ajaxParams = {
      uid: app.getUid(),
      gids: gids,
      nums: nums,
      aids: aids,
      addressid: addressId,
      couponids: couponId,
      isseckill: isseckill || 0,    //如果秒杀商品
      teamid: teamid || ""
    };
    if (isgroups == 1) {
      ajaxUrl = 'm=plugins&c=groupsadd';
      ajaxParams.isgroups = 1;
    }
    else {
      ajaxUrl = 'm=order&c=add&a=index';
    }
    //debugger;
    // if (actType && actType == 1) { //团购
    //   ajaxUrl = '/openapi/CActivity/groupBuyQuickOrder';
    //   ajaxParams.group_buy_id = this._groupBuyId;
    // }
    
    ajax.P({
      url: ajaxUrl,
      data: ajaxParams,
      success: (res) => {
        //debugger;
        if (res.code == 1) {
           util.showWarn(res.msg);
           return;
        };
        var result = res.data;
        $this.setData({
          orderId: result.id
        })
        var wxPayParams = {
          timeStamp: String(result.timestamp),
          nonceStr: result.nonce_str,
          package: result.package,
          paySign: result.sign
        }
        $this._paySuccess(wxPayParams);
      }
    });


    // ajax.P(ajaxUrl, ajaxParams, function (data) {
    //   var result = data.result;
    //   var {
    //             orderId,
    //     groupById: groupBuyId
    //         } = result;

    //   $this._groupBuyId = groupBuyId;
    //   $this.setData({
    //     orderId,
    //   });

    //   if (pay_type == 2) {
    //     var wxPayParams = JSON.parse(data.result.wxPayParams);
    //     $this._package = wxPayParams.package;
    //     var prepayArr = $this._package.split('=');
    //     common.submitPrepay(prepayArr[1]);
    //     $this._paySuccess(wxPayParams);
    //   } else if (pay_type == 3) {
    //     util.showOK('支付成功', function () {
    //       wx.redirectTo({
    //         url: '../orderList/orderList?ty=1'
    //       });
    //     });
    //   }
    // })
  },

  /**
   * 再次支付
   */
  _payAgain() {
    var $this = this;
    var activeIndex = this.data.activeIndex;
    var addressId = this.data.addressId;
    var orderType = this.data.orderType;
    var params = {
      openId: app.getOpenId(),
      orderId: this.data.orderId,
    };

    if (orderType == 5) {
      if (activeIndex == 0) { //配送订单
        orderType = 3;
      } else if (activeIndex == 1) { //到店消费
        orderType = 2;
      }
    }
    params.order_type = orderType;

    if (orderType == 3) {
      params.address_id = addressId;
    }

    var url = '/openapi/CHome/doPayAgain';

    if ($this._actType == 1) { //团购
      url = '/openapi/CActivity/doPayAgain';
    }

    ajax.P({
      url: ajaxUrl,
      data: ajaxParams,
      success: (res) => {

        var result = data.result;
        $this._paySuccess(JSON.parse(result.wxPayParams));

      }
    });
  },

  /**
   * 支付成功回调
   */
  _paySuccess(wxPayParams) {
    //debugger;
    wxUtil.wxPay(wxPayParams);
    // var _self = this;
    // var userCardNames = _self.data.userCardNames;
    // _self.setData({
    //   userCardNames: userCardNames.slice(0, 1)
    // })
    
    wxPayParams.success = function () {
      //debugger
      if (this.data.isgroups == 1){
        var url = '/pages/orderDetail/orderDetail?id=' + this.data.orderId + '&isgroups=1'
      }
      else{
        var url = '/pages/orderDetail/orderDetail?id=' + this.data.orderId;
      }
      wx.redirectTo({
        url
      });
    }.bind(this);

    wxPayParams.fail = function(){
      //debugger;
      var id = this.data.goodsId;
      if (this.data.isgroups == 1) {
          util.showWarn("支付失败", jump());
          function jump(){
            var url = '/pages/goods/detail2/detail?id=' + id;
            wx.redirectTo({
              url
            });
          }
      }
      else{
        var url = '/pages/orderDetail/orderDetail?id=' + this.data.orderId;
        wx.redirectTo({
          url
        });
      }

    }.bind(this);
  },
  /**
   * 选择地址
   */
  _goToAddr: function (e) {
    var formId = e.detail.formId;
    var orderId = this.data.orderId;
    if (orderId) {
      return util.alert('订单已生成，不能修改地址信息');
    }

    /*
    ** 这个是第一版写的,优化的目的是因为页面来回跳转带参数，实在感觉不好。所以换成了在跳转到的页面重新设置上一个页面的参数(比如:A->B,在B页面把B的数据付给A页面。用到的api:getCurrentPages())
    ***
    // var optionsStr = JSON.stringify(this._options);
    // if (!this.data.noAddr) {
    //     wx.navigateTo({
    //         url: '/pages/myAddr/myAddr?orderOptions=' + optionsStr,
    //     })
    // } else {
    //     wx.navigateTo({
    //         url: '/pages/selectedAddr/selectedAddr?orderOptions=' + optionsStr,
    //     })
    // }
    **/

    if (!this.data.noAddr) {
      wx.navigateTo({
        url: '/pages/my/selectAddr/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/my/myAddr/index',
      })
    }
    common.submitForm(formId);
  },
  /**
   * 切换优惠券列表
   */
  _toggleCouponsList(e) {
    var formId = e.detail.formId;
    this.setData({
      showDialog: !this.data.showDialog
    });
    if (typeof (formId) != "undefined") {
      common.submitForm(formId);
    }
  },
  /**
   * 加载优惠券列表
   */
  _getCouponList: function (couponCode, cb) {
    var self = this;
    var couponListLen = length;
    // var self = this;
    // var url = '/openapi/CCoupon/getOrderCouponList';
    // ajax.P(url, {
    //   couponCode: couponCode
    // }, function (data) {
    //   var couponList = data.result.list || [];
    //   var couponListLen = +data.result.list.length;
    //   var coupon = self.data.coupon;
    //   var toData = {
    //     couponList: couponList,
    //     couponListLen: couponListLen
    //   };
    //   var couponList = toData.couponList;
    //   if (data.result.list.length > 0) {
    //     couponList.forEach(function (item, index) {
    //       item.value = index;
    //       if (item.id == coupon.id) {
    //         item.checked = true;
    //       }
    //     });
    //   }
    //   self.setData(toData);
    //   cb && cb();
    // });
  },

  /**
   * 选择优惠券或原价支付
   */
  _switch1Change: function (e) {
    //debugger;
    var couponList = this.data.couponList;
    var orderAmount = this.data.orderAmount;
    var couponAmout = this.data.couponAmout;
    var toPayAmount = this.data.toPayAmount;
    var useCoupon = this.data.useCoupon;
    var couponId = this.data.couponId;
    var _self = this;
    //this._useCoupon = !useCoupon;
    var _useCoupon = !useCoupon;
    if (!_useCoupon) {
      couponList.some(function (item, index) {
        if (couponList[index].checked) {
          couponList[index].checked = false;
          _self.index = index;
        }
      })
      couponId = '';
      couponAmout = parseFloat(0).toFixed(2);
      toPayAmount = orderAmount;
    } else {
      couponList.some(function (item, index) {
        couponList[_self.index].checked = true;
        couponId = couponList[_self.index].id;
        couponAmout = parseFloat(couponList[_self.index].money).toFixed(2);
      })

      toPayAmount = (orderAmount - couponAmout).toFixed(2);
    }
    this.setData({
      couponId,
      couponAmout,
      toPayAmount,
      couponList,
      useCoupon: _useCoupon
    });
  },
  /**
   * 切换支付方式(微信支付或会员卡)
   */
  // _bindSelectPayMode: function (e) {

  //   var formId = e.detail.formId;
  //   var orderId = this.data.orderId;
  //   var couponList = this.data.couponList;
  //   var cardIndex = this.data.cardIndex;
  //   var userCardNames = this.data.userCardNames;
  //   var orderAmount = this.data.orderAmount;
  //   var toPayAmount = this.data.toPayAmount;
  //   var couponAmout = this.data.couponAmout;
  //   var userCard = this.data.userCard;
  //   var orderType = this.data.orderType;
  //   var activeIndex = this.data.activeIndex;
  //   var postage = this.data.postage;
  //   var rmPostAmount = this.data.rmPostAmount;

  //   if (orderId) {
  //     return util.alert('订单已生成，不能修改支付方式!');
  //   }

  //   cardIndex = e.currentTarget.dataset.value;

  //   if (cardIndex == 0) {
  //     if (this.data.coupon.length == 0) {
  //       toPayAmount = orderAmount;
  //     } else {
  //       couponAmout = !couponAmout ? parseFloat(this.data.coupon.coupon_amount).toFixed(2) || 0 : couponAmout;
  //       toPayAmount = (orderAmount - couponAmout).toFixed(2);
  //     }

  //     /*
  //     ** 这个是第一版写的,优化的目的是为了,尽可能少的setData
  //     ***
  //      this.setData({
  //          couponAmout: couponAmout,
  //          toPayAmount: toPayAmount
  //      });
  //     **/

  //   } else {
  //     //这个最初的目的是要在页面中添加会员卡的。。这个变量是给会员卡编号前面补‘0’用的(类似:00006);
  //     // userCard[cardIndex-1]['cid'] = this.PrefixInteger(userCard[cardIndex-1]['cid'],6);
  //     if (orderType == 3 || (orderType == 5 && activeIndex == 0)) {
  //       rmPostAmount = orderAmount - postage;
  //       if (userCard[cardIndex - 1].discount < 10) {
  //         toPayAmount = (orderAmount - postage) * userCard[cardIndex - 1].discount / 10 - (-postage);
  //       } else {
  //         toPayAmount = orderAmount;
  //       }
  //     } else {
  //       if (userCard[cardIndex - 1].discount < 10) {
  //         toPayAmount = orderAmount * userCard[cardIndex - 1].discount / 10;
  //       } else {
  //         toPayAmount = orderAmount;
  //       }
  //     }
  //     rmPostAmount = parseFloat(rmPostAmount).toFixed(2);
  //     toPayAmount = parseFloat(toPayAmount).toFixed(2);

  //     /*
  //     ** 这个是第一版的,优化的目的是为了,尽可能少的setData
  //     ***
  //      this.setData({
  //          rmPostAmount: parseFloat(rmPostAmount).toFixed(2),
  //          toPayAmount: parseFloat(toPayAmount).toFixed(2)
  //      })
  //     **/

  //   }
  //   this.setData({
  //     cardIndex,
  //     couponAmout,
  //     toPayAmount,
  //     rmPostAmount
  //   })
  //   common.submitForm(formId);
  // },
  /**
   * 从地址选择页面后，回来重新更新地址块
   */
  _resetAddr: function (addressId) {
    var _self = this;


    ajax.G({
      url: "m=user&c=address&a=info",
      data: {
         uid: app.getUid(),
         id: addressId
      },
      success: (res) => {

        var result = res.data;
        var address = {};

        //result 有值的时候返回 json格式，无值的时候返回array格式
        if (result.length != 0) {
          address.name = result.name;
          address.tel = result.tel;
          address.province = result.province;
          address.city = result.city;
          address.country = result.country;
          address.address = result.address;
         //address.is_default = result.is_default;
          addressId = result.id;
          _self.setData({
            address,
            addressId,
            noAddr: false
          })
        } else {
          _self.showSalt();
        }
      }
    });

  },

  /**
   * 选择优惠券
   */
  radioChange: function (e) {
    //debugger;
    var _self = this;
    var couponList = this.data.couponList;
    var couponAmout = this.data.couponAmout;
    var orderAmount = this.data.orderAmount;
    var toPayAmount = this.data.toPayAmount;
    var couponId = this.data.couponId;
    couponList.some(function (item, index) {
      couponList[index].checked = couponList[index].id == e.detail.value;
      if (couponList[index].checked) {
        couponId = couponList[index].id;
        couponAmout = parseFloat(couponList[index].money).toFixed(2);
        toPayAmount = (orderAmount - couponAmout).toFixed(2);
      }
    })
    this.setData({
      couponId,
      couponAmout,
      toPayAmount,
      couponList
    });
  },


  _jump: function (evt) {
    common.jump(evt);
  },

  // 到店自取还是快递配送
  radioChange2: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    var radioItems = this.data.radioItems;
    var isSelfGet = this.data.isSelfGet;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    };
    if (e.detail.value == 0){
      isSelfGet = 0
    }
    else{
      isSelfGet = 1
    };
    this.setData({
      radioItems: radioItems,
      isSelfGet: isSelfGet
    });
  },
}));
